package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/16 9:04
 * https://leetcode-cn.com/problems/combination-sum-iii/
 */
public class Title216 {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> list = new LinkedList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(n, k, 1);
        return result;
    }

    private void backTracking(int n, int k, int start) {
        if (list.size() == k) {
            if (sum == n) {
                result.add(new ArrayList<>(list));
            }
            return;
        }
        for (int i = start; i <= 9 - (k - list.size()) + 1; i++) {
            list.offer(i);
            sum += i;
            backTracking(n, k, i + 1);
            sum -= i;
            list.removeLast();
        }
    }






    public List<List<Integer>> combinationSum33(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> temp = new LinkedList<>();
        backTracking1(result, temp, n, k, 0, 1);
        return result;
    }

    private void backTracking1(List<List<Integer>> result, LinkedList<Integer> temp, int n, int k, int sum, int cur) {
        if (temp.size() == k) {
            if (sum == n) {
                result.add(new ArrayList<>(temp));
            }
            return;
        }
        for (int i = cur; i <= 9 + 1 + temp.size() - k; i++) {
            temp.add(i);
            backTracking1(result, temp, n, k, sum + i, i + 1);
            temp.removeLast();
        }
    }

    public static void main(String[] args) {

    }
}
